package com.ddx.controller.core;


import com.ddx.common.enums.PayType;
import com.ddx.common.enums.ResultType;
import com.ddx.common.exception.ExceptionUtil;
import com.ddx.common.exception.ResultModel;
import com.ddx.common.util.DataUtil;
import com.ddx.dto.ShoppingOrderVo;
import com.ddx.pay.MchOrderInfoResult;
import com.ddx.pay.WeChatPayDto;
import com.ddx.pay.WeixinPay;
import com.ddx.pojo.ShoppingOrder;
import com.ddx.pojo.ShoppingPayFlowWithBLOBs;
import com.ddx.pojo.ShoppingUserAddress;
import com.ddx.pojo.User;
import com.ddx.service.IAccountService;
import com.ddx.service.IShoppingCartService;
import com.ddx.service.IShoppingOrderService;
import com.ddx.service.IShoppingPayService;
import com.ddx.service.IShoppingUserCenterService;
import com.ddx.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 个人中心
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping({"/app/account"})
public class AccountController {
    private static Logger logger = LoggerFactory.getLogger(AccountController.class);
    @Autowired
    private IShoppingOrderService shoppingOrderService;
    @Autowired
    private IShoppingCartService shoppingCartService;
    @Autowired
    private IShoppingPayService shoppingPayService;
    @Autowired
    WeixinPay weixinPay;
    @Autowired
    IUserService iUserService;
    @Autowired
    IShoppingUserCenterService shoppingUserCenterService;

    @Autowired
    IAccountService accountService;

    /**
     * 支付
     *
     * @return
     */
    @RequestMapping({"/pay.do"})
    public ModelAndView pay(HttpServletRequest request) {
        String userId = request.getParameter("userId");
        String orderId = request.getParameter("orderId");
        logger.debug("{}支付订单：{}", userId, orderId);
        ModelAndView mv = new ModelAndView("/app/order/pay");
        try {
            User shoppingUser =iUserService.getUserInfo(userId);
            ShoppingOrder shoppingOrder = shoppingOrderService.orderInfo(orderId);
            mv.addObject("user", shoppingUser);
            mv.addObject("order", shoppingOrder);
        } catch (Exception e) {
            logger.error("AccountController", e);
            mv.addObject("error", e.getMessage());
        }
        return mv;
    }


    /**
     * 去支付
     *
     * @return
     */
    @RequestMapping({"/topay.do"})
    public @ResponseBody
    Object topay(HttpServletRequest request) {
        String userId = request.getParameter("userId");
        String orderId = request.getParameter("orderId");
        String type = request.getParameter("type");
        String payPassword = request.getParameter("payPassword");
        logger.debug("{}去支付：{}", userId, orderId);
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try {
            if (PayType.BALANCE_PAY.getValue().equals(type)) {
                User shoppingUser =iUserService.getUserInfo(userId);
//                if (shoppingUser.getPayPass() == null) {
//                    resultModel.setMsg("未设置支付密码！");
//                    resultModel.setCode("-404");
//                    return resultModel;
//                }
//                if (!payPassword.equals(shoppingUser.getPayPass())) {
//                    resultModel.setMsg("支付密码不正确！");
//                    resultModel.setCode("-1");
//                    return resultModel;
//                }
                shoppingPayService.balancePay(orderId);
                resultModel.setMsg(orderId);
            } else if (PayType.WECHAT_PAY.getValue().equals(type)) {
//                return "{\"code\":\"0\", \"msg\":\""+weChatPayDto.getMwebUrl()+"&redirect_url=http://2.yizhangjin.com.cn/paygate/paySuccess?orderId="+orderId+"\"}";
                WeChatPayDto weChatPayDto = shoppingPayService.WeChatPay(orderId, DataUtil.getIpAdrress(request));
                resultModel.setMsg(weChatPayDto.getMwebUrl());
//                        +"&redirect_url=http://"+ request.getServerName() + ":"+ request.getServerPort() +"/isPay.do?orderId="+orderId);
            }
        } catch (Exception e) {
            logger.error("AccountController", e);
            resultModel = ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }

    /**
     * 查询微信支付信息
     * @return
     */
    @RequestMapping({"/wxPayInfo.do"})
    public @ResponseBody
    Object delAddress(String orderId) {
        logger.debug("微信查询订单信息！orderId:"+orderId);
        ResultModel resultModel = ResultModel.getSuccessInstance();
        ShoppingOrderVo orderVo = shoppingOrderService.orderInfo(orderId);
        MchOrderInfoResult payOrderquery = weixinPay.payOrderquery(orderId);
        try{
            if("SUCCESS".equals(payOrderquery.getTrade_state())){
                // 这里是支付成功
                ShoppingPayFlowWithBLOBs shoppingPayFlow = new ShoppingPayFlowWithBLOBs();
                shoppingPayFlow.setOrderId(orderId);
                shoppingPayFlow.setAmount(orderVo.getPtotal());
                shoppingPayFlow.setDealStatus(ResultType.SUCCESS.getCode());
                shoppingOrderService.paySuccess(shoppingPayFlow);
            }
            resultModel.setMsg(payOrderquery.getTrade_state());
        }catch (Exception e) {
            logger.error("AccountController", e);
            resultModel = ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }
    /**
     * 支付完成
     * @return
     */
    @RequestMapping("/paySuccess.do")
    public ModelAndView paySuccess(String orderId) {
        logger.debug("支付完成！orderId:"+orderId);
        ModelAndView mv = new ModelAndView("/app/order/paySuccess");
        ShoppingOrderVo orderVo = shoppingOrderService.orderInfo(orderId);
        mv.addObject("orderVo", orderVo);
        return mv;
    }

    /**
     * 删除地址
     * @return
     */
    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/delAddress")
    public ResultModel delAddress(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        ResultModel resultModel = ResultModel.getSuccessInstance();
        String userId = request.getHeader("userId");
        try {
            Long addressId = Long.parseLong(map.get("addressId").toString());
            shoppingUserCenterService.delAddress(addressId, userId);
        } catch (Exception e) {
            logger.error("AccountController", e);
            resultModel = ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }

    /**
     * 保存地址
     * @return
     */
    @RequestMapping(value = "/saveAddress")
    @CrossOrigin(origins = "*", maxAge = 3600)
    public ResultModel saveAddress(@RequestBody ShoppingUserAddress address, HttpServletRequest request) {
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try{
            if(address.getId()==null||address.getId()==0){
                shoppingUserCenterService.saveAddress(address);
            }else {
                shoppingUserCenterService.updateAddress(address);
            }
        }catch (Exception e) {
            logger.error("AccountController", e);
            resultModel = ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }

    /**
     * 设为默认
     * @return
     */
    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/defaultAddress")
    public ResultModel defaultAddress(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        String userId = request.getHeader("userId");
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try{
            Long addressId = Long.parseLong(map.get("addressId").toString());
            shoppingUserCenterService.defaultAddress(addressId,userId);
        }catch (Exception e) {
            logger.error("AccountController", e);
            resultModel = ExceptionUtil.getMessageException(e);
            return resultModel;
        }
        return resultModel;
    }
    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/getAccountDetail")
    public  ResultModel getAccountDetail(HttpServletRequest request) {
        try {
            int userId = Integer.parseInt(request.getHeader("userId"));
            return accountService.getAccountDetail(userId);
        } catch (Exception e) {
            logger.error("getAccountDetail", e);
            return ExceptionUtil.getMessageException(e);
        }
    }

    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/address")
    public ResultModel address(HttpServletRequest request) {
        String userId = request.getHeader("userId");
        logger.debug("查询用户{}地址", userId);
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try{
            List<ShoppingUserAddress> list = shoppingUserCenterService.addressInfo(userId);
            Map<String,Object> map=new HashMap<>();
            map.put("addressList",list);
            resultModel.setData(map);
        }catch (Exception e) {
            logger.error("AccountController address{}", e);
            resultModel = ExceptionUtil.getMessageException(e);
            return resultModel;
        }
        return resultModel;
    }

    /**
     * 获取用户地址
     * @param request
     * @return
     */
    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/getDefaultAddress")
    public ResultModel getDefaultAddress(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        String userId = request.getHeader("userId");
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try {
            Map<String, Object> returnMap = new HashMap<>();
            if (map.get("addressId") != null) {
                ShoppingUserAddress defaultAddress = shoppingUserCenterService.getAddressInfo(map.get("addressId").toString());
                returnMap.put("defaultAddress", defaultAddress);
            } else {
                ShoppingUserAddress defaultAddress = shoppingUserCenterService.getDefaultAddress(userId);
                returnMap.put("defaultAddress", defaultAddress);
            }
            resultModel.setData(returnMap);
        } catch (Exception e) {
            logger.error("AccountController address{}", e);
            resultModel = ExceptionUtil.getMessageException(e);
            return resultModel;
        }
        return resultModel;
    }
    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/myAccount")
    public ResultModel myAccount(HttpServletRequest request) {
        String userId = request.getHeader("userId");
        logger.debug("查询财富{}", userId);
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try{
            Map<String,Object> map = shoppingUserCenterService.myAccount(userId);
            resultModel.setData(map);
        }catch (Exception e) {
            logger.error("AccountController myAccount{}", e);
            resultModel = ExceptionUtil.getMessageException(e);
            return resultModel;
        }
        return resultModel;
    }
}
